﻿using System;
using System.Net;
using System.Text;

namespace Kiva7.Utilities
{
    public class UrlCreator
    {
        private StringBuilder _Url = new StringBuilder();
        private bool _HasParameter = false;

        public UrlCreator()
        {
            _HasParameter = false;
        }

        public UrlCreator(string url)
        {
            _Url.Append(url);
            _HasParameter = url.Contains("?");
        }

        public UrlCreator(Uri uri)
        {
            string url = uri.ToString();
            _Url.Append(url);
            _HasParameter = url.Contains("?");
        }

        public void Add(string name, object value)
        {
            if (value == null)
            {
                return;
            }
            if (_HasParameter)
            {
                _Url.Append("&");
            }
            else
            {
                _Url.Append("?");
                _HasParameter = true;
            }
            _Url.Append(name);
            _Url.Append("=");
            _Url.Append(Convert(value));
        }

        private string Convert(object value)
        {
            if (value is bool)
            {
                bool b = (bool)value;
                if (b)
                {
                    return "1";
                }
                else
                {
                    return "0";
                }
            }
            else
            {
                return HttpUtility.UrlEncode(value.ToString());
            }
        }

        public Uri ToUri(UriKind uriKind)
        {
            return new Uri(_Url.ToString(), uriKind);
        }


        public Uri ToUri()
        {
            return new Uri(_Url.ToString());
        }

        public override string ToString()
        {
            return _Url.ToString();
        }
    }
}
